package com.example.farmeri.ui.farm_data;

import android.content.Intent;

import androidx.core.content.ContextCompat;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.example.farmeri.R;
import com.example.farmeri.pojo.Farm;
import com.example.farmeri.pojo.FarmDataT;
import com.example.farmeri.presenter.farm_data.FarmDataLookPresenter;
import com.example.farmeri.presenter.farm_data.IFarmDataLookContract;
import com.example.farmeri.tools.IdentUtils;
import com.example.farmeri.ui.base.BaseActivity;
import com.example.farmeri.ui.farm_manager.FarmManagerActivity;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.Description;
import com.github.mikephil.charting.components.LimitLine;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IndexAxisValueFormatter;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 农田数据详情页
 */
public class FarmDataLookActivity extends BaseActivity<FarmDataLookPresenter> implements IFarmDataLookContract {

    @BindView(R.id.farm_data_look_progress_all)
    ProgressBar pgsAll;
    @BindView(R.id.farm_data_look_progress_temperature)
    ProgressBar pgsTemperature;
    @BindView(R.id.farm_data_look_progress_humidity)
    ProgressBar pgsHumidity;
    @BindView(R.id.farm_data_look_progress_sun)
    ProgressBar pgsSun;

    @BindView(R.id.farm_data_look_chart_all)
    LineChart chartAll;
    @BindView(R.id.farm_data_look_chart_temperature)
    LineChart chartTemperature;
    @BindView(R.id.farm_data_look_chart_humidity)
    LineChart chartHumidity;
    @BindView(R.id.farm_data_look_chart_sun)
    LineChart chartSun;

    @BindView(R.id.text)
    TextView t;
    @BindView(R.id.text1)
    TextView h;
    @BindView(R.id.text3)
    TextView i;

    @BindView(R.id.name)
    TextView name;
    @BindView(R.id.address)
    TextView address;


    Map<Integer,Float > temperatureData;
    Map<Integer,Float > humidityData;
    Map<Integer,Float > sunData;

    Integer []color = {R.color.colorRed,R.color.colorBlue,R.color.colorAccent};


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_farm_data_look);
        ButterKnife.bind(this);
        init();
        //初始化toolbar
        initToolBar(R.id.farm_data_look_toolbar,"详情",true,true);
    }


    // 关闭数据加载状态，展示数据
    void showChart(){
        pgsAll.setVisibility(View.GONE);
        pgsHumidity.setVisibility(View.GONE);
        pgsSun.setVisibility(View.GONE);
        pgsTemperature.setVisibility(View.GONE);

        chartAll.setVisibility(View.VISIBLE);
        chartHumidity.setVisibility(View.VISIBLE);
        chartTemperature.setVisibility(View.VISIBLE);
        chartSun.setVisibility(View.VISIBLE);
    }


    private void init() {
        present = new FarmDataLookPresenter(this);

        Intent intent = getIntent();
        t.setText(intent.getStringExtra("t"));
        h.setText(intent.getStringExtra("h"));
        i.setText(intent.getStringExtra("i"));

        name.setText("田名：" + intent.getStringExtra("name"));
        address.setText("地址：" + intent.getStringExtra("address"));
        present.getFarmData(intent.getIntExtra("id",0)+"", "2019/04/27","2019/05/2");

    }


    private void initAllChart() {
        Map<Integer,String> date = present.getRecentDate(7);
        baseChart(chartAll);
        XAxis xAxis = chartAll.getXAxis();
        //设置X轴的刻度数量
        xAxis.setLabelCount(7,false);
        xAxis.setAxisMinimum(1f);
        xAxis.setAxisMaximum(7f);
        //得到月份
        xAxis.setValueFormatter(new IndexAxisValueFormatter(){
            @Override
            public String getFormattedValue(float value) {
            return date.get((int)value);
            }
        });
        List<Entry> temperatureCount = new ArrayList<>();
        List<Entry> humidityCount = new ArrayList<>();
        List<Entry> sunCount = new ArrayList<>();
        for (int i=0;i<temperatureData.size();i++) {
            temperatureCount.add(new Entry(i+1, temperatureData.get(i)));
            humidityCount.add(new Entry(i+1, humidityData.get(i)));
            sunCount.add(new Entry(i+1, sunData.get(i)));
        }
        LineDataSet temperatureDataSet = new LineDataSet(temperatureCount, "温度");
        LineDataSet humidityDataSet = new LineDataSet(humidityCount, "湿度");
        LineDataSet sunDataSet = new LineDataSet(sunCount, "光照");
        //温度
        temperatureDataSet.setColor(ContextCompat.getColor(this,color[0]));
        temperatureDataSet.setValueFormatter(new mIndexAxisValueFormatter());
        //湿度
        humidityDataSet.setColor(ContextCompat.getColor(this,color[1]));
        temperatureDataSet.setValueFormatter(new mIndexAxisValueFormatter());
        //光照
        sunDataSet.setColor(ContextCompat.getColor(this,color[2]));
        sunDataSet.setValueFormatter(new mIndexAxisValueFormatter());
        List<ILineDataSet> lineDataSetList = new ArrayList<>();
        if (IdentUtils.hasPower(IdentUtils.IDENT_TEMPERATURE)){
            lineDataSetList.add(temperatureDataSet);
        }
        if (IdentUtils.hasPower(IdentUtils.IDENT_HUMIDITY)) {
            lineDataSetList.add(humidityDataSet);
        }
        if (IdentUtils.hasPower(IdentUtils.IDENT_SUN)) {
            lineDataSetList.add(sunDataSet);
        }
        //线模式为圆滑曲线（默认折线）
        temperatureDataSet.setMode(LineDataSet.Mode.CUBIC_BEZIER);
        humidityDataSet.setMode(LineDataSet.Mode.CUBIC_BEZIER);
        sunDataSet.setMode(LineDataSet.Mode.CUBIC_BEZIER);
        // add entries to dataSet
        LineData lineData = new LineData(lineDataSetList);

        chartAll.setData(lineData);
        chartAll.invalidate(); // refresh
    }

    /**
     * 注意date是日期，data是数据
     * @param chart
     * @param color
     * @param label
     * @param data  数据
     */
    private void initSingleChart(LineChart chart, Integer color, String label, Map<Integer, Float> data) {
        Map<Integer,String> date = present.getRecentDate(7);
        baseChart(chart);
        XAxis xAxis = chart.getXAxis();
        //设置X轴的刻度数量
        xAxis.setLabelCount(7,false);
        xAxis.setAxisMinimum(1f);
        xAxis.setAxisMaximum(7f);
        //得到月份
        xAxis.setValueFormatter(new IndexAxisValueFormatter(){
            @Override
            public String getFormattedValue(float value) {
                return date.get((int)value);
            }
        });
        List<Entry> count = new ArrayList<>();
        for (int i=0;i<data.size();i++) {
            count.add(new Entry(i+1, data.get(i)) );
        }
        LineDataSet lineDataSet = new LineDataSet(count, label);
        lineDataSet.setColor(ContextCompat.getColor(this,color));
        lineDataSet.setValueFormatter(new IndexAxisValueFormatter(){
            @Override
            public String getFormattedValue(float value) {
                return String.valueOf((int)value);
            }
        });
        List<ILineDataSet> lineDataSetList = new ArrayList<>();
        lineDataSetList.add(lineDataSet);
        //线模式为圆滑曲线（默认折线）
        lineDataSet.setMode(LineDataSet.Mode.CUBIC_BEZIER);
        //设置折线图填充
        lineDataSet.setDrawFilled(true);
        // add entries to dataset
        LineData lineData = new LineData(lineDataSetList);

        chart.setData(lineData);
        chart.invalidate(); // refresh

    }

    protected void baseChart(LineChart chart){
        XAxis xAxis = chart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        //设置X轴坐标之间的最小间隔
        xAxis.setGranularity(1f);

        //警戒线
        LimitLine ll = new LimitLine(40, "预警值");
        ll.setLineWidth(1f);
        ll.setLineColor(color[0]);
        ll.setTextColor(color[0]);
        ll.setTextSize(12);
        ll.setEnabled(true);
        //得到Y轴
        YAxis rightYAxis = chart.getAxisRight();
        YAxis leftYAxis = chart.getAxisLeft();
        //添加警戒线
        leftYAxis.addLimitLine(ll);
        //隐藏
        rightYAxis.setEnabled(false);
        //限制Y轴高度
        leftYAxis.setAxisMinimum(0);
        //设置Y轴坐标之间的最小间隔
        leftYAxis.setGranularity(1f);
        //Description
        Description description = new Description();
        description.setEnabled(false);
        chart.setDescription(description);
        //是否展示网格线
        chart.setDrawGridBackground(false);
        //设置当前图表最多显示多少个刻度
        chart.setVisibleXRangeMaximum(6);
    }


    /**
     * 设置ToolBar内容
     * @param menu
     * @return
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu,menu);
        //添加编辑按钮
        MenuItem editAction = menu.add("编辑");
        editAction.setIcon(R.drawable.ic_edit_white_24dp);
        editAction.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
        editAction.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                Farm farm = getIntent().getParcelableExtra("farm");
                Intent intent = new Intent(FarmDataLookActivity.this, FarmDataEditActivity.class);
                intent.putExtra("id",getIntent().getIntExtra("id",2));
                intent.putExtra("farm",farm);
                startActivity(intent);
                return true;
            }
        });
        //添加新增管理员按钮
        //MenuItem addAction = menu.add("添加");
        //addAction.setIcon(R.drawable.ic_add_white_24dp);
        //addAction.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
        //addAction.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
        //    @Override
        //    public boolean onMenuItemClick(MenuItem item) {
        //        //startActivity(new Intent(FarmDataLookActivity.this, FarmDataEditActivity.class));
        //        Toast.makeText(FarmDataLookActivity.this,"新增管理员",Toast.LENGTH_SHORT).show();
        //        return true;
        //    }
        //});
        //添加查看管理员按钮
        MenuItem managerAction = menu.add("查看管理员");
        managerAction.setIcon(R.drawable.ic_insert_chart_white_24dp);
        managerAction.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
        managerAction.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                startActivity(new Intent(FarmDataLookActivity.this, FarmManagerActivity.class));
                //Toast.makeText(FarmDataLookActivity.this,"查看管理员",Toast.LENGTH_SHORT).show();
                return true;
            }
        });
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public void showMessage(String msg) {
        showToast(msg);
    }

    @Override
    public void onFarmDataResult(FarmDataT o) {
        showChart();
        temperatureData = present.getData(o.getTemperArray());
        humidityData = present.getData(o.getHumidiArray());
        sunData = present.getData(o.getIllumiArray());
        //初始化数据统计的图表
        initAllChart();
        if (IdentUtils.hasPower(IdentUtils.IDENT_TEMPERATURE)){
            //初始化温度的图表
            initSingleChart(chartTemperature,color[0],"温度",temperatureData);
        }
        if (IdentUtils.hasPower(IdentUtils.IDENT_HUMIDITY)) {
            //初始化湿度的图表
            initSingleChart(chartHumidity, color[1],"湿度", humidityData);
        }
        if (IdentUtils.hasPower(IdentUtils.IDENT_SUN)) {
            //初始化光照的图表
            initSingleChart(chartSun, color[2],"光照", sunData);
        }
    }

    @Override
    public void onFarmDataError(String msg) {
        showMessage(msg);
        showChart();
    }

    /**
     * 格式化图标的X轴数据
     */
    class mIndexAxisValueFormatter extends IndexAxisValueFormatter{
        @Override
        public String getFormattedValue(float value) {
            return String.valueOf((int)value);
        }
    }
}

